package com.jhgsys.internal.base.task;

import com.jhgsys.internal.base.entity.BaseArea;
import com.jhgsys.internal.base.entity.BaseAreaScheduling;
import com.jhgsys.internal.base.service.IBaseAreaSchedulingService;
import com.jhgsys.internal.base.service.IBaseAreaService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 排班定时任务
 * @author zhangwei
 * @date 2024-08-27 13:40:45
 */
@Slf4j
@Component
public class AreaSchedulingTask {
    public void buildTomorrowSchedule(){
        IBaseAreaService baseAreaService = SpringContextUtil.getBean(IBaseAreaService.class);
        IBaseAreaSchedulingService baseAreaSchedulingService = SpringContextUtil.getBean(IBaseAreaSchedulingService.class);
        List<BaseArea> baseAreaList = baseAreaService.findBaseAreaList(new BaseArea());
        if(!CollectionUtils.isEmpty(baseAreaList)){
            QueryRequest request = new QueryRequest();
            baseAreaList.forEach(i->{
                Date tomorrow = getNextDate();
                BaseAreaScheduling query = new BaseAreaScheduling();
                query.setSchedulingDate(tomorrow);
                query.setAreaId(i.getAreaId());
                List<BaseAreaScheduling> schedulings = baseAreaSchedulingService.findBaseAreaSchedulingPage(request,query).getRecords();
                if(CollectionUtils.isEmpty(schedulings)){
                    query.setSchedulingDate(null);
                    List<BaseAreaScheduling> newestSchedulings = baseAreaSchedulingService.findBaseAreaSchedulingPage(request,query).getRecords();
                    if(!CollectionUtils.isEmpty(newestSchedulings)){
                        BaseAreaScheduling newSchedule = BeanHelper.copyProperties(newestSchedulings.get(0), BaseAreaScheduling.class);
                        newSchedule.setAreaSchedulingId("");
                        newSchedule.setSchedulingDate(tomorrow);
                        baseAreaSchedulingService.save(newSchedule);
                    }
                }
            });
        }
    }

    private Date getNextDate(){
        LocalDate nextDay = LocalDate.now().plusDays(1);
        Date next = Date.from(nextDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        return next;
    }

}
